var Consts = require('../../../util/consts');
var messageService = require('../../../services/messageService');

module.exports = function (app) {
    return new ReconnectHandler(app);
};

var admin = 'backgroundAdmin';


var ReconnectHandler = function (app) {
    this.app = app;
};
var handler = ReconnectHandler.prototype;

/**
 * reconnect when error happened
 * @param msg
 * @param session
 * @param next
 */
handler.reconnect = function (msg, session, next) {
    var username = msg.username;
    var rid = session.get('rid');
    var self = this;

    var route = Consts.GameRoute.HIDE_AND_SEEK_GAME;
    var excludedAction = Consts.HAS_ACTION.UPDATE_SCOREBOARD;
    messageService.getLatestMessageExcludeAction(route, admin, rid, excludedAction, function (err, message) {
        if (err) {
            next(null, {code: 400, action: 'notPermitted'});
        } else {
            messageService.send(admin, username, message.content, rid, route, self.app);
            var equalAction = Consts.HAS_ACTION.UPDATE_SCOREBOARD;
            messageService.getLatestMessageEqualAction(route, admin, rid, equalAction, function (err, message) {
                messageService.send(admin, username, message.content, rid, route, self.app);
                next(null, {code: 200, action: 'otherActions'});
            });
        }
    });

};

